<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*

/*
 * qq服务类
 * 这里从webqq登录->qq登录->收发消息->退出登录
 */

/**
 * Description of qq
 *
 * @author Administrator
 */
class Qq_service extends CLI_Controller{
    private $node_hash_service = true;//node 服务中 计算获得好友列表中 哈希服务的状态  true为服务已经开启 flash为关闭
    private $speak_service = true;//bot的语言服务是否已经开启
    private $sms_service = true;// 短信服务是否开启
    private $qq;
	private $start_time = 0;//程序启动时间
	private $mysql_start_time = 0;//mysql连接时间
    public function __construct() {
        parent::__construct();
		$this->start_time = time();
		$this->mysql_start_time = time();
        $this->qq = new stdClass();
        $this->load->helper('qq');
        $this->load->helper('commonfun');
        $this->load->model('log_model','log');
        $this->load->helper('socket_post');
        $this->load->model('qq_chats_model');
        $this->load->config('node',true);
    }

    public function index()
    {
	echo 'QQ START';
        $this->load->library('qq/webqq');
        $this->_qq_init();
        $qq_num = CLI_FUN::scanf('请输入您的qq号:');
        $passwd = CLI_FUN::scanf('请输入您的qq密码:');
        $login = $this->webqq->login($qq_num,$passwd);
        
        if(true === $login)
        {
            $this->log->add('qq_server',$qq_num.':qq登陆成功','qq');
            while (true)
            {
				if($this->mysql_start_time < time()-3600)
				{
					$this->db->close();
					$this->load->database();
                    
					$this->log->add('mysql_connect_restart','mysql重置','qq');
					$this->mysql_start_time = time();
				}
                $poll = $this->webqq->poll();
                if(false === $poll)
                {
                    sleep(1);
                }
                else if(is_array($poll))
                {
                    foreach($poll as $item)
                    {
                        if($item['type'] == 'message')
                        {
                            $send_msg = $this->message_msg($item['msg'], $item['uin']);
                            $this->webqq->send_buddy($item['uin'],$send_msg);
                            \QQ\Common::echos("[{$item['username']}]发来的消息:{$item['msg']} --- 回复:{$send_msg}");
                            $this->_record($item['value'],$item['msg'],'message');
                        }
                        elseif($item['type'] == 'group_message')
                        {
                            if(!empty($item['card']) and strstr($item['msg'],'@'.$item['card']))
                            {
                                $msg = str_replace('@'.$item['card'],'',$item['msg']);
                                $send_msg = $this->message_msg($msg, $item['uin']);
                                $this->webqq->send_group($item['uin'],$send_msg);
                                \QQ\Common::echos("群:[{$item['username']}]发来的消息:{$item['msg']} --- 回复:{$send_msg}");
                                $this->_record($item['value'],$item['msg'],'group_message');
                            }
                            else
                            {
                                \QQ\Common::echos("群:[{$item['username']}][{$item['send_name']}]发来的消息:{$item['msg']} --- 回复:未回复");
                                $this->_record($item['value'],$item['msg'],'group_message');
                            }
                        }
                        elseif($item['type'] == 'verify_required')//处理好友验证
                        {
                            $this->_record($item['value'],$item['msg'],'verify_required');
                            $this->webqq->allow_and_add($item['account']);
                        }
                        elseif($item['type'] == 'buddies_status_change')//处理好友验证
                        {
                            $status = ($item['status'] == 'online')?'上线':'下线';
                            \QQ\Common::echos("好友:[{$item['username']}".$status);
                            //$this->_record($item['value'],$item['status'],'buddies_status_change');
                        }
                    }
                }
                else if(121 === $poll)
                {
                    $this->log->add('qq_server',$qq_num.':qq退出','qq');
                    exit;
                }
                else
                {
                    $this->log->add('qq_server','未知的错误:'.$poll,'qq');
                    \QQ\Common::echos('未知错误');
                }
            }
        }
    }
    
    /**
     * 获得回复的语句
     * 注意:这里的qq 不是qq号码  而是qq的uin值
     */
    public  function message_msg($content,$qq)
    {
        static $sms_qq = array();
        static $sms_count = array();
        if(isset($sms_qq[$qq]) && $sms_qq[$qq] == true) //判断是否需要发送短信
        {
            Socket_post::sms($content);
            $sms_count[$qq] = isset($sms_count[$qq])?$sms_count[$qq]++:1;
            $sms_qq[$qq] = false;
            return '短信已经发送了哦,您还有什么事情吗';
        }
        /* * 特定的处理方法 * */
        if(1 == $content)
        {
            if($this->sms_service)
            {
                $sms_qq[$qq] = true;
                return '好了现在输入您要给我主人发送的短信信息吧,我会帮你发送的';
                // return '额 短信接口暂停服务了';
            }
            else
            {
                return '啊哦 主人好像不想被打扰 把短信服务给关闭了';
            }
        }
        else if(2 == $content)
        {
            
        }
        if($this->speak_service)
        {
            return $this->reply($content);
        }
        else
        {
            return '主人把我的说话功能关了 我不知道怎么回答你啊';
        }
    }
    
    /**
     * 记录qq消息
     * @param object value
     * @param string msg
     * @param string type
     * @return int
     */
    private function _record($value,$msg,$type)
    {
        return $this->qq_chats_model->add(
                isset($value->value->msg_id)?$value->value->msg_id:'',
                isset($value->value->from_uin)?$value->value->from_uin:'',
                isset($value->value->to_uin)?$value->value->to_uin:'',
                isset($value->value->msg_id2)?$value->value->msg_id2:'',
                isset($value->value->msg_type)?$value->value->msg_type:'',
                isset($value->value->reply_ip)?$value->value->reply_ip:'',
                isset($value->value->time)?$value->value->time:'',
                var_export($value->value->content,true),
                $msg,
                $type
            );
    }
    
     /**
     * 初始化网络环境
     */
    protected function _qq_init() {
        /***********************************************************************************************************************/
        \QQ\Common::echo_system("初始化环境");
        ///检查qq服务器是否可以连接
        \QQ\Common::echo_system("检测qq服务器是否可以连接");
        $qq_server_network = $this->_server_network('web2.qq.com', '80');
        if($qq_server_network === 0)
        {
            \QQ\Common::echo_error("qq服务器连接失败,是否忽略,这可能不是您的网络原因");
             $t = \QQ\Common::scanf('');
            if(trim($t) == 'N')
            {
                \QQ\Common::echo_error("程序关闭");
                exit;
            }
        }
        elseif($qq_server_network === 1)
        {
            \QQ\Common::echo_system("qq服务器连接成功,网络情况良好");
        }
        elseif($qq_server_network === 2)
        {
            \QQ\Common::echo_warning("qq服务器连接成功,网络连接有点慢");
        }
        
		/***********************************************************************************************************************/
		//检查node中的p参数计算服务是否已经开启
        \QQ\Common::echo_system("检查node中的p参数计算服务是否已经开启");
        $qq_server_network = $this->_server_network($this->config->item('p_ip','node'), $this->config->item('p_port','node'));
        if($qq_server_network === 0)
        {
            \QQ\Common::echo_error("node中的p参数计算服务是必须的,您必须开启它");
            exit;
            $this->node_hash_service = false;
        }
		/***********************************************************************************************************************/
        //检查node中的hash计算服务是否已经开启
        \QQ\Common::echo_system("检查node中的hash计算服务是否已经开启");
        $qq_server_network = $this->_server_network($this->config->item('h_ip','node'), $this->config->item('h_port','node'));
        if($qq_server_network === 0)
        {
            \QQ\Common::echo_warning("node hash服务检测失败,这会导致好友列表获取失败,是否忽略继续执行:(Y/N)",'');
            $t = \QQ\Common::scanf('');
            if(trim($t) == 'N')
            {
                \QQ\Common::echo_error("程序关闭");
                exit;
            }
            $this->node_hash_service = false;
        }
        elseif($qq_server_network === 1)
        {
            \QQ\Common::echo_system("node hash服务器连接成功,网络情况良好");
        }
        elseif($qq_server_network === 2)
        {
            \QQ\Common::echo_warning("node hash服务器连接成功,网络连接有点慢");
        }
        
		/***********************************************************************************************************************/
        //检查电脑的语言交流系统是否已经开启
        \QQ\Common::echo_system("检查电脑的语言交流系统是否已经开启");
        $this->load->config('speak',true);
        $qq_server_network = $this->_server_network($this->config->item('speak_service_ip','speak'), $this->config->item('speak_service_port','speak'));
        if($qq_server_network === 0)
        {
            \QQ\Common::echo_warning("语言交流系统服务器开启失败，正在尝试启动,请耐心等待三秒");
            
            $common = 'nohup php index.php speak_service service  > speak.log 2>&1 &';
            \QQ\Common::echo_warning(system($common));
            if(0 === $this->_server_network($this->config->item('speak_service_ip','speak'), $this->config->item('speak_service_port','speak')))
            {
                \QQ\Common::echo_warning("尝试启动失败,你看可以选择是否忽略继续执行:(Y/N)",'');
                $t = \QQ\Common::scanf('');
                if(trim($t) == 'N')
                {
                    \QQ\Common::echo_error("程序关闭");
                    exit;
                }
                $this->speak_service = false;
            }
            else
            {
                \QQ\Common::echo_warning("语言交流尝试启动成功");
            }
        }
        elseif($qq_server_network === 1)
        {
            \QQ\Common::echo_system("语言交流系统服务器连接成功,网络情况良好");
        }
        elseif($qq_server_network === 2)
        {
            \QQ\Common::echo_warning("语言交流系统服务器连接成功,网络连接有点慢");
        }
        
		/***********************************************************************************************************************/
        //检查短信服务是否已经开启
        \QQ\Common::echo_system("检查短信服务是否已经开启");
        $this->load->config('sms',true);
        $qq_server_network = $this->_server_network($this->config->item('sms_service_ip','sms'), $this->config->item('sms_service_port','sms'));
        if($qq_server_network === 0)
        {
            \QQ\Common::echo_warning("短信系统服务器开启失败，正在尝试启动,请耐心等待三秒");
            \QQ\Common::echo_warning(system('nohup php index.php  sms_service service  > sms.log 2>&1 &'));
            if(0 === $this->_server_network($this->config->item('sms_service_ip','sms'), $this->config->item('sms_service_port','sms')))
            {
                \QQ\Common::echo_warning("尝试启动失败,你看可以选择是否忽略继续执行:(Y/N)",'');
                $t = \QQ\Common::scanf('');
                if(trim($t) == 'N')
                {
                    \QQ\Common::echo_error("程序关闭");
                    exit;
                }
                $this->sms_service = false;
            }
            else
            {
                \QQ\Common::echo_warning("短信系统尝试启动成功");
            }
        }
        elseif($qq_server_network === 1)
        {
            \QQ\Common::echo_system("短信交流系统服务器连接成功,网络情况良好");
        }
        elseif($qq_server_network === 2)
        {
            \QQ\Common::echo_warning("短信交流系统服务器连接成功,网络连接有点慢");
        }
        \QQ\Common::echo_system("检测成功开始登录qq程序");
		/***********************************************************************************************************************/
    }
    
    /**
     * 检测服务器网络是否可以连接
     * return  0:连接失败   1:连接成功网络状态良好 2:连接成功 ping值偏大
     */
    protected function _server_network($url,$port=80)
    {
        $ping_time = 0;
        $ping_count = 3; //ping的次数
        for($i=0;$i<$ping_count;$i++)
        {
            $t = ping($url,$port);
            if(false == $t)
            {
                return 0;
                break;
            }
            $ping_time += $t;
        }
        $ping = ceil($ping_count/$ping_time);
        if($ping < 20)
        {
            return 1;
        }
        else
        {
            return 2;
        }
    }
    
    /**
     * 获得回复的内容
     */
    function reply($msg)
    {
        $this->load->library("autoresponders");
        $data = $this->autoresponders->msg($msg);
        if($data != false)
        {
              return  $data;
        }
        else
        {
              return $this->config->item('speak_msg','speak');
        }
     }
}
